import rosbag2_py
import rosbag
import rclpy
from rclpy.node import Node

class BagConverter(Node):
    def __init__(self, ros2_bag_path, ros1_bag_path):
        super().__init__('bag_converter')
        self.ros2_bag_path = ros2_bag_path
        self.ros1_bag_path = ros1_bag_path
        self.convert_bag()

    def convert_bag(self):
        # Open ROS2 bag
        storage_options = rosbag2_py.StorageOptions(uri=self.ros2_bag_path, storage_id='sqlite3')
        converter_options = rosbag2_py.ConverterOptions()
        reader = rosbag2_py.SequentialReader()
        reader.open(storage_options, converter_options)

        # Create ROS1 bag
        ros1_bag = rosbag.Bag(self.ros1_bag_path, 'w')

        while reader.has_next():
            (topic, data, t) = reader.read_next()
            # You may want to transform the topic name here if needed
            ros1_bag.write(topic, data, t)

        ros1_bag.close()

def main(ros2_bag_path, ros1_bag_path):
    rclpy.init()
    converter = BagConverter(ros2_bag_path, ros1_bag_path)
    rclpy.shutdown()

if __name__ == '__main__':
    main('path_to_your_ros2_bag', 'path_to_your_ros1_bag.bag')

